﻿package  {

	import flash.events.*;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.utils.ByteArray;
	
	public class FileOpenHelper extends EventDispatcher {
		
		private var fileRef:FileReference;
		private var textTypeFilter:FileFilter;
		
		public function FileOpenHelper() {
			// constructor code
			fileRef = new FileReference();
			textTypeFilter = new FileFilter("JSON (*.json)","*.json");
			fileRef.addEventListener(Event.SELECT, onFileSelected);
			fileRef.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
		}
		
		public function startBrowse():void {
			fileRef.browse([textTypeFilter]);
		}

		private function onFileSelected(evt:Event):void {
			fileRef.addEventListener(ProgressEvent.PROGRESS, onProgress);
			fileRef.addEventListener(Event.COMPLETE, onComplete);
			fileRef.load();
		}
		
		public function save(data:String):void {
			var fileName:String = fileRef.name;
			fileRef = new FileReference();
			fileRef.save(data, fileName);
		}
		private function onProgress(event:ProgressEvent):void {
			trace("Loaded " + event.bytesLoaded + " of " + event.bytesTotal + " bytes.");
		}
		
		private function onComplete(event:Event):void {
			dispatchEvent(new Event(Event.OPEN));
		}
		
		private function onIOError(evt:IOErrorEvent):void {
			trace("There was an IO Error.");
		}
		
		private function onSecurityError(evt:Event):void {
			trace("There was a security error.");
		}
		
		public function getData():String {
			return fileRef.data.toString();
		}
	}
	
}
